package com.tencent.wuyanzu.whattoeat.util;

import android.util.Log;

import com.tencent.wuyanzu.whattoeat.Entity.Food;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by maiffany on 16/7/24.
 */
public class ParseJSONFoodData {
    public static List<Food> getFood(String json) {

        try {
            JSONObject jsonObject = new JSONObject(json);
            JSONObject foodJsonObj = jsonObject.getJSONObject("init");
            JSONArray foodArray = foodJsonObj.getJSONArray("food");
            return getFoodFromJsonArray(foodArray);

        } catch (JSONException e) {
            Log.e("ParseJsonFoodData","getFood() error " + e.toString());
            e.printStackTrace();
        }
        return new ArrayList<Food>();

    }


    public static List<Food> getFoodFromJsonArray(JSONArray foodArray ) {
        List<Food> foods = new ArrayList<Food>();

        try {
            for (int i = 0; i < foodArray.length(); i++) {
                JSONObject o = (JSONObject) foodArray.get(i);
                Food food = new Food();
                food.setAddress(o.getString("address"));
                food.setDescription(o.getString("description"));
                food.setDown(o.getInt("down"));
                food.setUp(o.getInt("up"));
                food.setName(o.getString("name"));
                //food.setPhoneNumber(o.getString("number"));
                food.setUrl(o.getString("url"));
                foods.add(food);
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        return foods;
    }
    public Map<String, List<Food>> getUidFoodMapper(String json){
        Map<String, List<Food>> map = new HashMap<>();
        JSONObject jsonObject = null;
        try {
            jsonObject = new JSONObject(json);
            String uid = jsonObject.getString("uid");
            List<Food> foods = getFood(json);
            map.put(uid,foods);
        } catch (JSONException e) {
            Log.e("ParseJsonFoodData","getUidFoodMapper() error " + e.toString());
            e.printStackTrace();
        }

        return map;
    }
}
